#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include "gmssl/sm4.h"

// 不再重新定义 SM4_BLOCK_SIZE
// #define SM4_BLOCK_SIZE 16

// 函数声明
void handleErrors(const char *message);
void sm4_decrypt_file(const char *key_file, const char *input_file, const char *output_file);

int main(int argc, char *argv[]) {
    if (argc != 4) {
        fprintf(stderr, "Usage: %s <key_file> <input_file> <output_file>\n", argv[0]);
        return EXIT_FAILURE;
    }

    sm4_decrypt_file(argv[1], argv[2], argv[3]);

    return EXIT_SUCCESS;
}

void sm4_decrypt_file(const char *key_file, const char *input_file, const char *output_file) {
    FILE *kf, *inf, *outf;
    SM4_KEY sm4_key;
    uint8_t key[SM4_KEY_SIZE];
    uint8_t input[SM4_BLOCK_SIZE];
    uint8_t output[SM4_BLOCK_SIZE];
    size_t bytes_read;

    // 打开密钥文件
    kf = fopen(key_file, "rb");
    if (!kf) {
        handleErrors("Failed to open key file");
    }

    // 读取密钥
    if (fread(key, 1, SM4_KEY_SIZE, kf) != SM4_KEY_SIZE) {
        fclose(kf);
        handleErrors("Failed to read key from file");
    }
    fclose(kf);

    // 设置 SM4 解密密钥
    sm4_set_decrypt_key(&sm4_key, key);

    // 打开输入文件
    inf = fopen(input_file, "rb");
    if (!inf) {
        handleErrors("Failed to open input file");
    }

    // 打开输出文件
    outf = fopen(output_file, "wb");
    if (!outf) {
        fclose(inf);
        handleErrors("Failed to open output file");
    }

    // 逐块读取输入文件并进行解密
    while ((bytes_read = fread(input, 1, SM4_BLOCK_SIZE, inf)) > 0) {
        // 调用 sm4_encrypt 进行解密
        sm4_encrypt(&sm4_key, input, output);
        fwrite(output, 1, SM4_BLOCK_SIZE, outf);
    }

    fclose(inf);
    fclose(outf);
    printf("Decryption completed successfully.\n");
}

void handleErrors(const char *message) {
    fprintf(stderr, "Error: %s\n", message);
    exit(EXIT_FAILURE);
}
